package com.yanx.common.security;

import cn.hutool.http.HttpStatus;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.yanx.common.result.Result;
import com.yanx.common.security.model.LoginVo;
import com.yanx.common.security.service.TokenService;
import com.yanx.common.utils.Json_;
import com.yanx.common.utils.Message_;
import com.yanx.common.utils.Servlet_;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.*;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

/**
 * spring security配置
 *
 * @author gotanks
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfig {
    /**
     * 自定义用户认证逻辑
     */
    @Autowired
    private UserDetailsService userDetailsService;

    /**
     * token认证过滤器
     */
    @Autowired
    private JwtAuthenticationTokenFilter authenticationTokenFilter;

    /**
     * token服务
     */
    @Autowired
    private TokenService tokenService;

    /**
     * anyRequest          |   匹配所有请求路径
     * access              |   SpringEl表达式结果为true时可以访问
     * anonymous           |   匿名可以访问
     * denyAll             |   用户不能访问
     * fullyAuthenticated  |   用户完全认证可以访问（非remember-me下自动登录）
     * hasAnyAuthority     |   如果有参数，参数表示权限，则其中任何一个权限可以访问
     * hasAnyRole          |   如果有参数，参数表示角色，则其中任何一个角色可以访问
     * hasAuthority        |   如果有参数，参数表示权限，则其权限可以访问
     * hasIpAddress        |   如果有参数，参数表示IP地址，如果用户IP和参数匹配，则可以访问
     * hasRole             |   如果有参数，参数表示角色，则其角色可以访问
     * permitAll           |   用户可以任意访问
     * rememberMe          |   允许通过remember-me登录的用户访问
     * authenticated       |   用户登录后可访问
     */
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                .csrf().disable()// CRSF禁用，因为不使用session
                .cors()//开启跨域
                .and()

                // 不允许iframe内呈现
                .headers().frameOptions().disable()
                .and()

                // 基于token，所以不需要session
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()

                // 过滤请求
                .authorizeRequests()
                .antMatchers("/login", "/register", "/test", "/captchaImage", "/api/auth/**", "/api/weixin/pay/notify/order", "/api/weixin/pay/test").permitAll()
                .antMatchers(HttpMethod.GET, "/*.html", "/**/*.html", "/**/*.css", "/**/*.js", "/**/*.css.map", "/**/*.js.map", "/**/*.ico", "/profile/**").permitAll()
                .antMatchers("/**/v2/api-docs", "/**/swagger-ui.html", "/**/swagger-resources").permitAll()
                .anyRequest().authenticated()// 除上面外的所有请求全部需要鉴权认证
                .and()

                // 认证失败
                .exceptionHandling()
                .authenticationEntryPoint(authenticationEntryPoint())
                .and()

                // 登录
//                .formLogin()
//                .successHandler(successHandler())
//                .failureHandler(failureHandler())
//                .permitAll()
//                .and()

                // 登出
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessHandler(logoutSuccessHandler())
                .and()

                // 添加JWT filter
                .addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
        return httpSecurity.build();

    }

    private LogoutSuccessHandler logoutSuccessHandler() {
        return (request, response, authentication) -> {
            LoginUser loginUser = tokenService.getLoginUser(request);
            String message = Message_.message("user.logout.success");
            if (loginUser != null) {
                // 删除用户缓存记录
                tokenService.delLoginUser(loginUser.getUuid());
                // 记录用户退出日志
//                AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGOUT, "退出成功"));
                LoginInforRecordUtils.success(loginUser.getUsername(), message);
            }
            Result<Object> result = new Result<>();
            result.setCode(HttpStatus.HTTP_OK);
            result.setMsg(message);
            Servlet_.renderString(response, Json_.toJson(result));
        };
    }

    private AuthenticationEntryPoint authenticationEntryPoint() {
        return (req, resp, authException) -> {
            Result<Object> result = new Result<>();
            result.setCode(HttpStatus.HTTP_UNAUTHORIZED);
            result.setMsg("尚未登录，请先登录");
            Servlet_.renderString(resp, Json_.toJson(result), HttpStatus.HTTP_UNAUTHORIZED);
        };
    }

    private AuthenticationSuccessHandler successHandler() {
        return (req, resp, authentication) -> {
            LoginUser loginUser = (LoginUser) authentication.getPrincipal();
            String token = tokenService.createToken(loginUser);
            LoginVo loginVo = new LoginVo(token, loginUser.getUsername(), loginUser.get("nickName"));

            Result<Object> result = new Result<>();
            result.setCode(HttpStatus.HTTP_OK);
            result.setData(loginVo);
            Servlet_.renderString(resp, Json_.toJson(result));
        };
    }

    private AuthenticationFailureHandler failureHandler() {
        return (req, resp, e) -> {
            Result<Object> result = new Result<>();
            result.setCode(HttpStatus.HTTP_FORBIDDEN);
            result.setMsg(e.getMessage());
            if (e instanceof LockedException) {
                result.setMsg("账户被锁定，请联系管理员!");
            } else if (e instanceof CredentialsExpiredException) {
                result.setMsg("密码过期，请联系管理员!");
            } else if (e instanceof AccountExpiredException) {
                result.setMsg("账户过期，请联系管理员!");
            } else if (e instanceof DisabledException) {
                result.setMsg("账户被禁用，请联系管理员!");
            } else if (e instanceof BadCredentialsException) {
                result.setMsg("用户名或者密码输入错误，请重新输入!");
            }
            Servlet_.renderString(resp, Json_.toJson(result), HttpStatus.HTTP_FORBIDDEN);
        };
    }

    /**
     * 认证管理
     *
     * @param httpSecurity
     * @return
     * @throws Exception
     */
    @Bean
    public AuthenticationManager authenticationManager(HttpSecurity httpSecurity) throws Exception {
        return httpSecurity.getSharedObject(AuthenticationManagerBuilder.class)
                .userDetailsService(userDetailsService)
                .passwordEncoder(bCryptPasswordEncoder())
                .and()
                .build();
    }

    /**
     * 强散列哈希加密实现
     */
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

}
